
using Microsoft.IdentityModel.Tokens;
using StudentVideo.Common.Constants;
using StudentVideo.Shared.Enums;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace StudentVideo.Helper;

public class JwtHelper(IConfiguration configuration) {
   private readonly IConfiguration _configuration = configuration;

   public string GenerateJwtToken(string uid, UserRangeEnum UserRangeEnum) {
      var jwtSettings = _configuration.GetSection("Jwt");
      var secretKey = jwtSettings["SecretKey"];
      var issuer = jwtSettings["Issuer"];
      var audience = jwtSettings["Audience"];
      var expirationMinutes = double.Parse(jwtSettings["ExpirationMinutes"]!);

      var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey!));
      var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

      // 定义用户的声明信息
      var claims = new[] {
         new Claim(UserClaims.Uid, uid),
         new Claim(UserClaims.UserRange, UserRangeEnum.ToString())
      };

      // 创建 Token
      var token = new JwtSecurityToken(
          issuer: issuer,
          audience: audience,
          claims: claims,
          expires: DateTime.Now.AddMinutes(expirationMinutes),
          signingCredentials: credentials
      );

      // 返回序列化后的 Token 字符串
      return new JwtSecurityTokenHandler().WriteToken(token);
   }
}
